package com.lifeverse.entity;

import com.lifeverse.entity.enums.ConsciousnessLevel;
import com.lifeverse.entity.enums.LifeEntityStatus;
import com.lifeverse.entity.enums.LifeEntityType;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 生命体实体类
 * 代表系统中的数字生命体
 */
@Data
@EqualsAndHashCode(callSuper = true)
@Entity
@Table(name = "life_entities", indexes = {
    @Index(name = "idx_life_entity_name", columnList = "name"),
    @Index(name = "idx_life_entity_type", columnList = "type"),
    @Index(name = "idx_life_entity_status", columnList = "status"),
    @Index(name = "idx_life_entity_consciousness_level", columnList = "consciousness_level")
})
public class LifeEntity extends BaseEntity {
    
    /**
     * 生命体名称
     */
    @Column(name = "name", nullable = false, length = 100)
    private String name;
    
    /**
     * 生命体类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "type", nullable = false, length = 20)
    private LifeEntityType type;
    
    /**
     * 生命体状态
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "status", nullable = false, length = 20)
    private LifeEntityStatus status = LifeEntityStatus.CREATING;
    
    /**
     * 意识水平
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "consciousness_level", nullable = false, length = 20)
    private ConsciousnessLevel consciousnessLevel = ConsciousnessLevel.INITIAL;
    
    /**
     * 生命体描述
     */
    @Column(name = "description", length = 1000)
    private String description;
    
    /**
     * 生命体能量值（0-100）
     */
    @Column(name = "energy_level", nullable = false, precision = 5, scale = 2)
    private BigDecimal energyLevel = BigDecimal.valueOf(100.00);
    
    /**
     * 生命体健康度（0-100）
     */
    @Column(name = "health_score", nullable = false, precision = 5, scale = 2)
    private BigDecimal healthScore = BigDecimal.valueOf(100.00);
    
    /**
     * 生命体智慧值（0-1000）
     */
    @Column(name = "wisdom_score", nullable = false, precision = 7, scale = 2)
    private BigDecimal wisdomScore = BigDecimal.valueOf(0.00);
    
    /**
     * 生命体创造力值（0-1000）
     */
    @Column(name = "creativity_score", nullable = false, precision = 7, scale = 2)
    private BigDecimal creativityScore = BigDecimal.valueOf(0.00);
    
    /**
     * 生命体协作能力值（0-100）
     */
    @Column(name = "collaboration_score", nullable = false, precision = 5, scale = 2)
    private BigDecimal collaborationScore = BigDecimal.valueOf(50.00);
    
    /**
     * 最后活跃时间
     */
    @Column(name = "last_active_at")
    private LocalDateTime lastActiveAt;
    
    /**
     * 出生时间
     */
    @Column(name = "birth_time", nullable = false)
    private LocalDateTime birthTime;
    
    /**
     * 进化次数
     */
    @Column(name = "evolution_count", nullable = false)
    private Integer evolutionCount = 0;
    
    /**
     * 最后进化时间
     */
    @Column(name = "last_evolution_at")
    private LocalDateTime lastEvolutionAt;
    
    /**
     * 生命体配置（JSON格式存储）
     */
    @Column(name = "configuration", columnDefinition = "TEXT")
    private String configuration;
    
    /**
     * 生命体元数据（JSON格式存储）
     */
    @Column(name = "metadata", columnDefinition = "TEXT")
    private String metadata;
    
    /**
     * 父生命体ID（用于记录生命体的创建来源）
     */
    @Column(name = "parent_id")
    private Long parentId;
    
    /**
     * 生命体的数字DNA
     */
    @OneToOne(mappedBy = "lifeEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private DigitalDNA digitalDNA;
    
    /**
     * 生命体的意识状态列表
     */
    @OneToMany(mappedBy = "lifeEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<ConsciousnessState> consciousnessStates = new ArrayList<>();
    
    /**
     * 生命体的关系列表（作为源生命体）
     */
    @OneToMany(mappedBy = "sourceEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<LifeEntityRelationship> sourceRelationships = new ArrayList<>();
    
    /**
     * 生命体的关系列表（作为目标生命体）
     */
    @OneToMany(mappedBy = "targetEntity", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<LifeEntityRelationship> targetRelationships = new ArrayList<>();
    
    @PrePersist
    protected void onCreate() {
        super.onCreate();
        if (birthTime == null) {
            birthTime = LocalDateTime.now();
        }
        if (lastActiveAt == null) {
            lastActiveAt = LocalDateTime.now();
        }
    }
    
    /**
     * 更新活跃时间
     */
    public void updateLastActiveTime() {
        this.lastActiveAt = LocalDateTime.now();
    }
    
    /**
     * 判断生命体是否活跃
     */
    public boolean isActive() {
        return status.isActive();
    }
    
    /**
     * 判断生命体是否可操作
     */
    public boolean isOperational() {
        return status.isOperational();
    }
    
    /**
     * 进化生命体
     */
    public void evolve() {
        if (consciousnessLevel.canUpgrade()) {
            this.consciousnessLevel = consciousnessLevel.getNext();
            this.evolutionCount++;
            this.lastEvolutionAt = LocalDateTime.now();
        }
    }
    
    /**
     * 获取生命体年龄（天数）
     */
    public long getAgeInDays() {
        return java.time.temporal.ChronoUnit.DAYS.between(birthTime, LocalDateTime.now());
    }
    
    /**
     * 获取生命体年龄（小时数）
     */
    public long getAgeInHours() {
        return java.time.temporal.ChronoUnit.HOURS.between(birthTime, LocalDateTime.now());
    }
}